package com.mzsoft.ai;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.mzsoft.ai.service.OperateDataService;
import com.mzsoft.ai.utils.file.FileUtil;

public class DataFallbackApplication {

    private static Logger logger = LoggerFactory.getLogger(DataFallbackApplication.class);

    public static void main(String[] args) {

        logger.debug("代码回退start.............");

        String userDir = System.getProperty("user.dir");
        String configPath = userDir+"/config/servers.json";
        logger.info("userDir:"+userDir);
        if(!new File(configPath).exists()){
            throw new RuntimeException("回退脚本文件【"+configPath+"】不存在!");
        }

        try{
            String appServerMapStr = FileUtil.getFileContent(configPath);
            logger.debug("appServerMapStr:"+appServerMapStr);
            Map<String,Object> appServerMap = JSON.parseObject(appServerMapStr, Map.class);
            logger.debug("jdbc链接信息:"+JSON.toJSONString(appServerMap));

            for(String businessCode : appServerMap.keySet()){
                operateFallbackData(businessCode,appServerMap);
            }

        }catch (Exception e){
           logger.error(e.getMessage(),e);
        }

        logger.debug("代码回退end.............");
    }

    /**
     * 业务操作不同文件夹下的excel数据
     * @param businessCode
     * @param appServerMap
     */
    private static void operateFallbackData(String businessCode, Map<String, Object> appServerMap) throws SQLException, IOException {

        logger.debug("fallBack business data start ......");

        Map<String,Object> appServer = (Map<String, Object>) appServerMap.get(businessCode);
        String folderPath = (String) appServer.get("folderPath");

        logger.debug("folderPath:"+folderPath);
        List<String> sqlList = (List<String>) appServer.get("fallBackList");
        logger.debug("fileList:"+JSON.toJSONString(sqlList));
        OperateDataService.fallBackData(folderPath,sqlList);

        logger.debug("fallBack business data end ......");
    }
}
